<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\CacheService;
use App\Services\UserService;
use App\Services\ConfigService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

/**
 * 登录模块
 * Class LoginController
 * @package App\Http\Controllers
 */
class LoginController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        // 验证码校验
        if (!isset($request->captcha_id) || !isset($request->captcha_code)) {
            return $this->error(__('login.captcha_code_empty'));
        }
        $captcha_code = CacheService::pull($request->captcha_id);
        if (empty($captcha_code) || !hash_equals(strtolower($request->captcha_code), strtolower($captcha_code))) {
            return $this->error(__('login.error_captcha_code'));
        }
        // 数据校验
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required'
        ], [
            'username.required' => __('login.username_required'),
            'password.required' => __('login.password_required'),
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $user = User::where(['username' => $request->username, 'status' => 1])->select(['id', 'password', 'sys'])->first();

        // 关闭登录校验
        $allowLogin = ConfigService::getConfigItemValue("login", "allow_login");
        if($user && !$user->sys && !$allowLogin ) {
            return $this->errorLogin(__('login.error_allow_login'));
        }

        if (!$user) {
            return $this->errorLogin(__('login.error_user_password'));
        }

        // 超记录错误次数提示
        if (!UserService::validateLoginFailTimes($user)) {
            return $this->errorLogin(UserService::loginFailTimesTips());
        }

        // 验证密码
        if (!Hash::check($request->password, $user->password)) {
            UserService::recordLoginFailTimes($user);
            return $this->errorLogin(__('login.error_user_password'));
        }

        // 清空登录错误次数
        UserService::clearLoginFailTimes($user, true);

        // 分配token
        $token = $user->createToken('console-token')->plainTextToken;
        $data = [
            'token' => $token
        ];
        return $this->successLogin($data);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        $user_id = $request->user()->id;
        // 清除缓存
        CacheService::clear();
        return $this->success(__('login.success_logout'));
    }
}
